package com.mohe.shanpao.netty.protobuf;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpUtil;
import io.netty.handler.codec.http.HttpVersion;

public class HttpProtobufServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
		
		FullHttpResponse response= new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
		response.content().writeBytes(request.content());
		
		ByteBuf buf = response.content();
		int bytes = response.content().readableBytes();
		byte[] data = new byte[bytes];
		buf.readBytes(data);
		CommandProto.Command c = CommandProto.Command.parseFrom(data);
		System.out.println(c.getName());
		
		HttpUtil.setContentLength(response, response.content().readableBytes());
		ChannelFuture f = ctx.writeAndFlush(response);
		
		if (!HttpUtil.isKeepAlive(request) || response.status().code() != 200) {
			System.out.println("closed channel from "+ctx.channel().localAddress());
			f.addListener(ChannelFutureListener.CLOSE);
		}
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.close();
	}

}
